package me.numark.fragments;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.numark.R;
import me.numark.model.DailyData;
import me.numark.model.Feed;
import me.numark.model.FeedListResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Utils;
import me.numark.view.FeedViewHolder;

/**
 * Created by Evan on 15/8/9.
 */
public class HotFragment extends BaseListFragment {

    HotAdapter mHotAdapter;
    Calendar today;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataList = new ArrayList();
        mHotAdapter = new HotAdapter();
        mAdapter = mHotAdapter;
    }

    @Override
    public void initUI(View view) {
        super.initUI(view);
        setHasMore(true);
    }

    @Override
    protected String cacheKey() {
        return "hot_marks";
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, FeedListResponse.class);
    }

    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        Calendar date = null;
        if (dataList.size() > 0) {
            DailyData data = (DailyData) dataList.get(dataList.size() - 1);
            date = (Calendar) data.date.clone();
            date.add(Calendar.DATE, -1);
        } else {
            date = today;
        }
        loadData(date, 0);
    }

    @Override
    public void onRefresh() {
        today = Utils.getToday();
        loadData(today, 0);
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {

    }

    void bindData(FeedListResponse response, Calendar date, int start) {
        boolean isToday = date.compareTo(today) == 0;
        if (isToday && start == 0)
            super.bindData(response, true);
        synchronized (HotFragment.class) {
            if (dataList.size() > 0) {
                DailyData theDay = (DailyData) dataList.get(0);
                if (date.compareTo(theDay.date) > 0 && start == 0) {
                    dataList.clear();
                }
            }
            int i = 0;
            for (; i < dataList.size(); i++) {
                DailyData theDay = (DailyData) dataList.get(i);
                if (date.compareTo(theDay.date) == 0) {
                    break;
                }
            }
            if (i == dataList.size()) {
                DailyData newDay = new DailyData();
                newDay.date = date;
                dataList.add(newDay);
            }
            DailyData theDay = (DailyData) dataList.get(i);
            if (start == 0) {
                theDay.data.clear();
            }
            for (Feed feed : response.data) {
                if (!theDay.data.contains(feed)) {
                    theDay.data.add(feed);
                }
            }
            theDay.hasMore = response.has_more;
            if (!theDay.hasMore && start == 0 && response.data.length == 0 && i == dataList.size() - 1) {
                Calendar nextDate = (Calendar) theDay.date.clone();
                nextDate.add(Calendar.DATE, -1);
                loadData(nextDate, 0);
            }
            int pos = 0;
            for (i = 0; i < dataList.size(); i++) {
                theDay = (DailyData) dataList.get(i);
                theDay.startPos = pos;
                pos += theDay.data.size() + (theDay.hasMore ? 1 : 0);
            }
        }
        mAdapter.notifyDataSetChanged();
        if (mAdapter.getAdapterItemCount() == 0) {
            showEmptyView();
        } else {
            recyclerView.hideEmptyView();
        }
    }

    public void loadData(final Calendar date, final int start) {
        new RequestServerTask<FeedListResponse>(FeedListResponse.class) {
            @Override
            protected String requestServer() {
                String url = String.format(NetworkConstants.HOT_MARK_URL, Global.getCurrentUid());
                Map<String, Object> params = new HashMap<String, Object>();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) + 1;
                int day = date.get(Calendar.DATE);
                params.put("date", String.format("%d-%d-%d", year, month, day));
                params.put("start", String.valueOf(start));
                params.put("limit", String.valueOf(Constants.HOT_PAGE_SIZE));
//                if (start > 0 && lastResponseTime > 0) {
//                    params.put("time", String.valueOf(lastResponseTime));
//                }
                return HttpUtil.get(url, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                for (int i = 0; i < dataList.size(); i++) {
                    DailyData theDay = (DailyData) dataList.get(i);
                    if (date.compareTo(theDay.date) == 0) {
                        theDay.isRefreshing = false;
                        break;
                    }
                }
                endRefreshing();
            }

            @Override
            protected void onSuccess(FeedListResponse result) {
                bindData(result, date, start);
            }
        }
                .setSnackbarView(rootView)
                .start();
    }

    public class HotAdapter extends UltimateViewAdapter<FeedViewHolder> {
        @Override
        public FeedViewHolder getViewHolder(View view) {
            return new FeedViewHolder(view, HotFragment.this, Constants.FEEDTYPE_NONE,false);
        }

        @Override
        public FeedViewHolder onCreateViewHolder(ViewGroup viewGroup) {
            View v = LayoutInflater.from(getActivity())
                    .inflate(R.layout.feed_list_item, viewGroup, false);
            FeedViewHolder vh = new FeedViewHolder(v, HotFragment.this, Constants.FEEDTYPE_HOT_MARK,false);
            return vh;
        }

        @Override
        public FeedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 4) {
                View view = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.load_more, parent, false);
                return new FeedViewHolder(view, HotFragment.this, Constants.FEEDTYPE_LOADMORE,false);
            }

            return super.onCreateViewHolder(parent, viewType);
        }

        @Override
        public int getAdapterItemCount() {
            synchronized (HotFragment.class) {
                if (dataList.size() > 0) {
                    DailyData data = (DailyData) dataList.get(dataList.size() - 1);
                    return data.startPos + data.data.size() + (data.hasMore ? 1 : 0);
                }
            }
            return 0;
        }

        @Override
        public long generateHeaderId(int i) {
            return 0;
        }

        @Override
        public void onBindViewHolder(FeedViewHolder holder, int position) {
            Object data = getItem(position);
            if (data == null)
                return;
            if (data instanceof Feed) {
                Feed feed = (Feed) data;
                holder.bindData(feed,this,position);
            } else if (data instanceof DailyData) {
                DailyData day = (DailyData) data;
                holder.bindData(day);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
            return null;
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {

        }

        Object getItem(int position) {
            synchronized (HotFragment.class) {
                for (int i = 0; i < dataList.size(); i++) {
                    DailyData theDay = (DailyData) dataList.get(i);
                    if (theDay.startPos + theDay.data.size() == position) {
                        if (theDay.hasMore)
                            return theDay;
                    } else if (theDay.startPos + theDay.data.size() > position) {
                        return theDay.data.get(position - theDay.startPos);
                    }
                }
            }
            return null;
        }

        @Override
        public int getItemViewType(int position) {
            int type = position == this.getItemCount() - 1 && this.customLoadMoreView != null ? (this.isLoadMoreChanged ? 3 : 2) : (position == 0 && this.customHeaderView != null ? 1 : 0);
            if (type == 0) {
                if (getItem(position) instanceof DailyData)
                    return 4;
                return 0;
            }
            return type;
        }

        public void remove(int position) {
            remove(dataList, position);
        }

        public void clear() {
            clear(dataList);
        }

        @Override
        public void remove(List<?> list, int position) {
            super.remove(list, position);
        }

        public void removeFromUser(){
            HotFragment.this.refresh();
        }
    }
}
